﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace WenAntdUI.Helps
{
    internal class PropertyHelp
    {

    }

    public class Notify<T> : INotifyPropertyChanged where T : class, new()
    {
        public object? GetValue<TProperty>(Expression<Func<T, TProperty>> propertyExpression)
        {
            if (propertyExpression.Body is MemberExpression memberExpression)
            {
                var propertyName = memberExpression.Member.Name;
                return this[propertyName];
            }
            throw new ArgumentException("无效的属性表达式。");
        }

        public void SetValue<TProperty>(Expression<Func<T, TProperty>> propertyExpression, TProperty value)
        {
            if (propertyExpression.Body is MemberExpression memberExpression)
            {
                var propertyName = memberExpression.Member.Name;
                this[propertyName] = value;
            }
            else
            {
                throw new ArgumentException("无效的属性表达式。");
            }
        }
        private readonly T _model;

        public Notify(T model)
        {
            _model = model ?? throw new ArgumentNullException(nameof(model));
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 获取或设置模型的属性值
        /// </summary>
        /// <param name="propertyName">属性名称</param>
        /// <returns>属性值</returns>
        public object? this[string propertyName]
        {
            get
            {
                var property = typeof(T).GetProperty(propertyName);
                if (property == null)
                    throw new ArgumentException($"属性 {propertyName} 不存在于类型 {typeof(T).Name} 中。");
                return property.GetValue(_model);
            }
            set
            {
                var property = typeof(T).GetProperty(propertyName);
                if (property == null)
                    throw new ArgumentException($"属性 {propertyName} 不存在于类型 {typeof(T).Name} 中。");

                var currentValue = property.GetValue(_model);
                if (!Equals(currentValue, value))
                {
                    property.SetValue(_model, value);
                    OnPropertyChanged(propertyName);
                }
            }
        }

        /// <summary>
        /// 通知属性更改
        /// </summary>
        /// <param name="propertyName">属性名称</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
